import sys
from pathlib import Path
current_file_path = Path(__file__)
project_root = current_file_path.parent.parent.parent
sys.path.append(str(project_root))

import simpy
import logging

from model import (
    Node,
    SimpleClock,
    TdmaSimpleMac,
    RadioChannel,
    RadioPhy,
    recorder
)

from model.mobility import (
    Position,
    ConstantSpeed,
    LinearMobility,
    TrajectoryMobility,
    RandomWaypointMobility,
)

logger = logging.getLogger('Test')

CLOCK_FREQ_HZ = 1000000
CLOCK_SKEW_PPM = 0
CLOCK_MAX_VALUE = 50000
TX_FREQ = 4500000000
TX_POWER_DB = 40
RX_SENSITIVITY = -110
SIM_DURATION = 20



def set_logger_level(name, level):
    logger = logging.getLogger(name)
    logger.setLevel(level)

def setup_logging():
    logging.basicConfig(
        level=logging.WARNING,
        format='%(name)12s - %(levelname)6s - %(message)s',
    )
    set_logger_level('RadioChannel', logging.INFO)
    set_logger_level('RadioPhy', logging.INFO)
    set_logger_level('TdmaSimpleMac', logging.DEBUG)
    #set_logger_level('Record', logging.DEBUG)

if __name__ == '__main__':

    setup_logging()
    
    logger.info(f"Starting radio test second simulation...")
    
    env = simpy.Environment()
    
    nodes = [Node(env, i) for i in range(4)]
    channel = RadioChannel(env, nodes)
    
    nodes[0].set_position(Position(0, 0, 0))
    nodes[0].set_mobility(LinearMobility(ConstantSpeed(175), destination=Position(1000, 0, 1000)))

    nodes[1].set_position(Position(0, 0, 0))
    nodes[1].set_mobility(LinearMobility(ConstantSpeed(160), destination=Position(0, 1000, 1000)))

    nodes[2].set_position(Position(0, 0, 0))
    nodes[2].set_mobility(TrajectoryMobility(ConstantSpeed(180), waypoints=[
        Position(500, 0, 250),
        Position(500, 500, 500),
        Position(0, 500, 750),
        Position(0, 1000, 1000),
    ]))

    nodes[3].set_position(Position(0, 0, 0))
    nodes[3].set_mobility(RandomWaypointMobility(ConstantSpeed(500), 
        x_range=[-1000, 1000],
        y_range=[-1000, 1000],
        z_range=(0, 1000)))

    for n in nodes:
        clock = SimpleClock(env, CLOCK_FREQ_HZ, 0, CLOCK_MAX_VALUE, CLOCK_SKEW_PPM)
        phy = RadioPhy(env, clock, 200, 800, 5000, 10)
        phy.set_channel(channel)
        phy.set_node(n)
        n.set_phy(phy)
        phy.set_tx_freq(TX_FREQ)
        phy.set_tx_power(TX_POWER_DB)
        phy.set_rx_sensitivity(RX_SENSITIVITY)
        mac = TdmaSimpleMac(env, n, phy)
        mac.start()

    # 运行仿真
    env.run(SIM_DURATION)
    logger.info("Simulation finished.")
    recorder.save('RadioTestSecond.json')